//
//  UserEditViewController.m
//  CheekiOS
//
//  Created by mac on 2017/6/16.
//  Copyright © 2017年 mac. All rights reserved.
//

#import "UserEditViewController.h"
//点击头像选择照片弹框
#import "GGActionSheet.h"
//修改姓名
#import "UserEditNameSexCell.h"
#import "UserEditNameController.h"
//修改年龄
#import "UserEditAgeController.h"
//修改身高体重
#import "XDPickView.h"
//修改职业
#import "UserEditProfessionalController.h"
//情感
#import "UserEditEmotionalController.h"
//修改标签
#import "UserTheLabelController.h"

@interface UserEditViewController ()<UITableViewDelegate, UITableViewDataSource,UINavigationControllerDelegate,UIImagePickerControllerDelegate,GGActionSheetDelegate,XDPickerDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIImageView *headimageView;
@property (nonatomic, strong) UserpersionlInfoModel *infoModel;
@property (nonatomic, strong) GGActionSheet *actionSheetTitle;
@property (nonatomic, strong) XDPickView *heightWeithView;
@property (nonatomic, strong) NSString *heightWeithType;
@property (nonatomic, strong) NSString *heightWeithStr;
@property (nonatomic, strong) NSString *PickRowStr;
@property (nonatomic, strong) NSMutableArray  *proTitleList;
@property (nonatomic, strong) UIView *BackGView;
@end

@implementation UserEditViewController

- (void)viewWillAppear:(BOOL)animated{
    [self requestUserInfo];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setNavgationBarHiddenNo];
    [self selfTitleFontColor];
    self.title = @"编辑资料";
    _heightWeithType = @"0";
       [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(requestUserInfo) name:@"UserEditNameUpdateNotifiction" object:nil];
    if (!_tableView) {
        self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, KScreenHeight-49) style:UITableViewStylePlain];
        self.tableView.delegate = self;
        self.tableView.dataSource = self;
        self.tableView.backgroundColor = [UIColor whiteColor];
        self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [self.view addSubview:_tableView];
    }

    [self.tableView reloadData];

}
#pragma ======获得个人信息========
- (void)requestUserInfo{
        [HcardHttpmanager getPersionalInfosuccess:^(id sucess) {
            self.infoModel = [UserpersionlInfoModel mj_objectWithKeyValues:sucess[@"res"]];
            NSLog(@"%@",self.infoModel);
            [self.tableView reloadData];
            
        } failure:^(NSError *error) {
            
        }];
}

#pragma mark ================tableViewdelegate datasource===============

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 1;
    }else{
        return 10;
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        static NSString *UserEditImageIdent = @"UserEditImageIdent";
        
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:UserEditImageIdent];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:UserEditImageIdent];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.backgroundColor = RGB(234, 234, 234);
            
        }
        UIView *backView = [[UIView alloc] init];
        backView.frame = CGRectMake(0, 10, KScreenWidth, 72.5);
        backView.backgroundColor = Theme_Color_White;
        
        UILabel *headLab = [[UILabel alloc] init];
        headLab.frame = CGRectMake(15, 0, 100, backView.height);
        headLab.font = FontBold(15);
        headLab.textColor = [UIColor blackColor];
        headLab.text = @"头像";
        [backView addSubview:headLab];
        
        _headimageView = [[UIImageView alloc] init];
        _headimageView.frame = CGRectMake(backView.right-75, 6.25, 60, 60);
        [_headimageView.layer setMasksToBounds:YES];
        _headimageView.layer.cornerRadius = 30;
        _headimageView.contentMode = UIViewContentModeScaleAspectFill;
        [_headimageView sd_setImageWithURL:[NSURL URLWithString:HttpImgUrl(_infoModel.photo)] placeholderImage:[UIImage imageNamed:@"llustration"]];
        [backView addSubview:_headimageView];
        
        [cell addSubview:backView];
        return cell;

    }else if (indexPath.section == 1){
        //修改姓名，年龄，性别，身高，体重，职业，情感，签名，标签
            UserEditNameSexCell *cell = [UserEditNameSexCell cellWithTableView:tableView indexPath:indexPath];
            cell.infoModel = _infoModel;
            
            return cell;
    }
 

    return nil;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return 92.5;
    }else{
        return 55;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0) {
        [self headerImageViewAction];
        NSLog(@"修改头像");
    }else if (indexPath.section == 1){
        if (indexPath.row == 0) {
            UserEditNameController *NameVc = [[UserEditNameController alloc] init];
            NameVc.typeStr = @"0";
            NameVc.titleStr = @"昵称";
            [self.navigationController pushViewController:NameVc animated:YES];
            NSLog(@"修改姓名");
        }else if (indexPath.row == 1){
            UserEditAgeController *AgeVc = [[UserEditAgeController alloc] init];
            AgeVc.ageStr = _infoModel.age;
            AgeVc.constellationStr = _infoModel.star;
            [self.navigationController pushViewController:AgeVc animated:YES];
            NSLog(@"修改年龄");
        }else if(indexPath.row == 3){
            _heightWeithType = @"0";

            [self showBackGView:_heightWeithType];
            NSLog(@"修改身高");
        }else if (indexPath.row == 4){
            _heightWeithType = @"1";

            [self showBackGView:_heightWeithType];
            NSLog(@"修改体重");

        }else if (indexPath.row == 5){
            UserEditProfessionalController *NameVc = [[UserEditProfessionalController alloc] init];
            
            [self.navigationController pushViewController:NameVc animated:YES];
            NSLog(@"职业");

        }else if(indexPath.row == 6){
            UserEditEmotionalController *vc = [[UserEditEmotionalController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
            NSLog(@"情感");
        }else if (indexPath.row == 7){
            UserEditNameController *NameVc = [[UserEditNameController alloc] init];
            NameVc.typeStr = @"1";
            NameVc.titleStr = @"签名";
            [self.navigationController pushViewController:NameVc animated:YES];
            NSLog(@"修改个性签名");
            
        }else if(indexPath.row == 8){
            UserTheLabelController *vc = [[UserTheLabelController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
            NSLog(@"修改个性标签");

        }
    }
    
}

#pragma mark ==============修改身高 体重==========
//实例化选择器
- (void)showBackGView:(NSString *)str{
    
    self.BackGView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, KScreenHeight)];
    self.BackGView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.0];
    _PickRowStr = @"";
    _PickRowStr = str;

    
    UILabel *ChoiceLab = [[UILabel alloc] init];
    ChoiceLab.frame = CGRectMake(25, 119, KScreenWidth-50, 50);

    ChoiceLab.text = @"选择";
    ChoiceLab.textAlignment = NSTextAlignmentCenter;
    ChoiceLab.textColor = [UIColor blackColor];
    ChoiceLab.font = FontBold(15);

    ChoiceLab.backgroundColor = Colorbackground;
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:ChoiceLab.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(9, 9)];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = ChoiceLab.bounds;
    maskLayer.path = maskPath.CGPath;
    ChoiceLab.layer.mask = maskLayer;
    

    [self.BackGView addSubview:ChoiceLab];

  
    
    _heightWeithView = [[XDPickView alloc] initWithFrame:CGRectMake(25, ChoiceLab.bottom, KScreenWidth-50, 200)];
    _heightWeithView.heightWeithStr = str;
    _heightWeithView.delegate = self;
    _heightWeithView.backgroundColor = Theme_Color_White;
    _heightWeithView.contentTextColor = [UIColor blackColor];
    _heightWeithView.LieWidth = 80;
    _proTitleList = [NSMutableArray array];
    
    if ([str isEqualToString:@"0"]) {
        for (int i=100; i<230; i++) {
            
            [_proTitleList addObject:[NSString stringWithFormat:@"%d",i]];
        }

    }else{
        for (int i=10; i<150; i++) {
            
            [_proTitleList addObject:[NSString stringWithFormat:@"%d",i]];
        }

    }
    _heightWeithView.pickViewTextArray = self.proTitleList;//设置数据
    if ([str isEqualToString:@"0"]) {
        [_heightWeithView MoRenSelectedRowWithObject:@"150"];//默认选中的哪一项
        _heightWeithStr =@"150";

    }else{
        [_heightWeithView MoRenSelectedRowWithObject:@"60"];//默认选中的哪一项
        _heightWeithStr =@"60";

    }
    [self.BackGView addSubview:_heightWeithView];
    
    
    
    UIButton *ConfirmBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    ConfirmBtn.frame = CGRectMake(25, _heightWeithView.bottom, _heightWeithView.width, 50);

    [ConfirmBtn addTarget:self action:@selector(ConfirmBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [ConfirmBtn setTitle:@"确定" forState:UIControlStateNormal];
    ConfirmBtn.titleLabel.font = FontBold(15);
    [ConfirmBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    ConfirmBtn.backgroundColor = Colorbackground;
    ConfirmBtn.alpha = 1;
    ConfirmBtn.tag = 100;
    UIBezierPath *BtnmaskPath = [UIBezierPath bezierPathWithRoundedRect:ConfirmBtn.bounds byRoundingCorners:UIRectCornerBottomLeft | UIRectCornerBottomRight cornerRadii:CGSizeMake(9, 9)];
    CAShapeLayer *BtnmaskLayer = [[CAShapeLayer alloc] init];
    BtnmaskLayer.frame = ConfirmBtn.bounds;
    BtnmaskLayer.path = BtnmaskPath.CGPath;
    ConfirmBtn.layer.mask = BtnmaskLayer;
    
    [self.BackGView addSubview:ConfirmBtn];
    
    
    UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    cancelBtn.frame = CGRectMake(KScreenWidth/2-25,ConfirmBtn.bottom+42 , 50, 50);
    [cancelBtn setBackgroundImage:[UIImage imageNamed:@"p_center_bjzl_qxan_button"] forState:UIControlStateNormal];
    [cancelBtn addTarget:self action:@selector(ConfirmBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    cancelBtn.tag = 101;
    [self.BackGView addSubview:cancelBtn];

    
    

    [self animationWithView:self.BackGView duration:0.3];
    
    [UIView animateWithDuration:0.25 animations:^{
        self.BackGView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.3];
        ChoiceLab.alpha = 1;
        ConfirmBtn.alpha = 1;

        [self.view addSubview:self.BackGView];
    }];
    

    
}
//确认 取消按钮方法
- (void)ConfirmBtnClick:(UIButton *)sender{
    if (sender.tag == 100) {
        if ([_PickRowStr isEqualToString:@"0"]){
       
            NSDictionary *dict = @{
                                   @"height":_heightWeithStr,
                                   @"uid":[HQHttpManager getUserId]
                                   };
            [self updateUser:dict];
        }else{
            NSDictionary *dict = @{
                                   @"weight":_heightWeithStr,
                                   @"uid":[HQHttpManager getUserId]
                                   };
            [self updateUser:dict];

        }
    }
    [_heightWeithView removeFromSuperview];
    [_BackGView removeFromSuperview];
}
#pragma mark -- XDPickViewDelegate 的代理方法必须实现
-(void)PickerSelectorIndixString:(NSString *)str{
    NSLog(@"str%@",str);
    _heightWeithStr = str;
}
//展示动画
- (void)animationWithView:(UIView *)view duration:(CFTimeInterval)duration{
    
    CAKeyframeAnimation * animation;
    animation = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
    animation.duration = duration;
    animation.removedOnCompletion = NO;
    
    animation.fillMode = kCAFillModeForwards;
    
    NSMutableArray *values = [NSMutableArray array];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.1, 0.1, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.2, 1.2, 1.0)]];
    //    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.9, 0.9, 0.9)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.0, 1.0, 1.0)]];
    
    animation.values = values;
    animation.timingFunction = [CAMediaTimingFunction functionWithName: @"easeInEaseOut"];
    
    [view.layer addAnimation:animation forKey:nil];
}



#pragma mark ================弹框选择===============
- (void)headerImageViewAction{
    [self.actionSheetTitle showGGActionSheet];
}
-(GGActionSheet *)actionSheetTitle{
    if (!_actionSheetTitle) {
        
        _actionSheetTitle = [GGActionSheet ActionSheetWithTitleArray:@[@"拍照",@"从手机相册选择"] andTitleColorArray:@[[UIColor blackColor]] delegate:self];
        //取消按钮颜色设置
        _actionSheetTitle.cancelDefaultColor = [UIColor blackColor];
        //如果设置了选项颜色 当颜色数组和标题数组数量对不上时 多余标题使用选项默认颜色
        //如果设置了选项颜色 当颜色数组传空时，所有选项默认使用选项颜色
        //如果没设置选项颜色 数量对不上以及颜色数组为空时都使用默认黑色
        _actionSheetTitle.optionDefaultColor = [UIColor blackColor];
    }
    return _actionSheetTitle;
}
//弹框点击
-(void)GGActionSheetClickWithActionSheet:(GGActionSheet *)actionSheet Index:(int)index{
    
    
    
    if (index == 1) {
        NSLog(@"手机");
        [self addPhoto];

    }else{
        NSLog(@"拍照");
        [self takePhoto];


    }
    
}
#pragma mark ====================修改头像========================
- (void)addPhoto {
    
    
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    
    [picker.navigationBar setBackgroundImage:[UIImage imageNamed:@"NagavitionBarImg"] forBarMetrics:UIBarMetricsDefault];
    
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    
    picker.delegate = self;
    //设置选择后的图片可被编辑
    picker.allowsEditing = YES;
    [self presentViewController:picker animated:YES completion:^{
        
    }];
    
}
- (void)takePhoto {
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera])
    {
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        
        //设置拍照后的图片可被编辑
        picker.allowsEditing = YES;
        picker.sourceType = sourceType;
        
        [self presentViewController:picker animated:YES completion:^{
            
        }];
    }else
    {
        NSLog(@"模拟器中无法打开照相机,请在真机中使用");
    }
}
-(void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    
    //当选择的类型是图片
    if ([type isEqualToString:@"public.image"]){
        
        //切忌不可直接使用originImage，因为这是没有经过格式化的图片数据，可能会导致选择的图片颠倒或是失真等现象的发生，从UIImagePickerControllerOriginalImage中的Origin可以看出
        UIImage* oldImage = [info objectForKey:UIImagePickerControllerEditedImage];
        
        //图片压缩，因为原图都是很大的，不必要传原图
        UIImage *scaleImage = [self scaleImage:oldImage toScale:0.3];
        
        UIImageOrientation imageOrientation = scaleImage.imageOrientation;
        
        UIImage * image;
        if(imageOrientation!=UIImageOrientationUp)
        {
            // 原始图片可以根据照相时的角度来显示，但UIImage无法判定，于是出现获取的图片会向左转９０度的现象。
            // 以下为调整图片角度的部分
            UIGraphicsBeginImageContext(scaleImage.size);
            [scaleImage drawInRect:CGRectMake(0, 0, scaleImage.size.width, scaleImage.size.height)];
            image = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();
            // 调整图片角度完毕
        }else{
            image = scaleImage;
        }
        NSData *data;
        
        if (UIImagePNGRepresentation(image) == nil){
            data = UIImageJPEGRepresentation(image, 1.0);
        }
        else{
            data = UIImagePNGRepresentation(image);
        }
        
        
        //图片保存的路径
        //这里将图片放在沙盒的documents文件夹中
        NSString * DocumentsPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
        
        //文件管理器
        NSFileManager *fileManager = [NSFileManager defaultManager];
        
        //把刚刚图片转换的data对象拷贝至沙盒中 并保存为image.jpg
        [fileManager createDirectoryAtPath:DocumentsPath withIntermediateDirectories:YES attributes:nil error:nil];
        [fileManager createFileAtPath:[DocumentsPath stringByAppendingString:@"/image.png"] contents:data attributes:nil];
        
        UIImage * img = [UIImage imageWithData:data];

  
        
        //先传到文件路径 在传给服务器
        [HcardHttpmanager upLoadPhotosWithFile:img WithBelong:@"photo" WithToAublum:KToAublumNO WithAlbumId:nil success:^(id sucess) {
            [SVProgressHUD dismiss];
            if(sucess){
                NSDictionary *dict = @{
                                       @"uid":[HQHttpManager getUserId],
                                       @"photo":sucess
                                       };
                //关闭相册界面
              
                
                [self updateUser:dict];
            }else{
                [SVProgressHUD showErrorWithStatus:@"上传失败!"];
            }
        } failure:^(NSError *error) {
            [SVProgressHUD dismiss];
            [SVProgressHUD showErrorWithStatus:@"上传失败!"];
        }];
        
        [SVProgressHUD showWithStatus:@"正在上传"];
        [picker dismissViewControllerAnimated:YES completion:^{
            
            UIImage * img = [UIImage imageWithData:data];
            
            self.headimageView.image = img;
            
        }];
   

        
    }
    
}
//头像传给服务器
-(void)updateUser:(NSDictionary *)dict{
    [HcardHttpmanager MakePersionalInfoWithParam:dict success:^(id sucess) {
        if(sucess){
            [HcardHttpmanager getPersionalInfosuccess:^(id sucess) {
                self.infoModel = [UserpersionlInfoModel mj_objectWithKeyValues:sucess[@"res"]];
                [_tableView reloadData];

            } failure:^(NSError *error) {
                NSLog(@"%@",error.description);
            }];
            
        }
    } failure:^(NSError *error) {
        
    }];
}
//压缩图片
-(UIImage *)scaleImage:(UIImage *)image toScale:(float)scaleSize
{
    UIGraphicsBeginImageContext(CGSizeMake(image.size.width*scaleSize,image.size.height*scaleSize));
    [image drawInRect:CGRectMake(0, 0, image.size.width * scaleSize, image.size.height *scaleSize)];
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaledImage;
}
/**
 *  用户点击取消按钮时调用
 */
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    
    [picker dismissViewControllerAnimated:YES completion:^{
        
    }];
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

@end
